package com.example.l3.ktm;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;

import com.example.l3.ktm.browserdownload;
import com.example.l3.ktm.newdownload;
import com.example.l3.ktm.DownloadUtility.*;
import com.example.l3.ktm.ListView.CellDataItem;
import com.example.l3.ktm.ListView.CustomCellAdapter;
public class DownloadManager extends Activity {

	private Button btnBrowser;
	private Button btnNew;
	private Button btnPause;
	private ListView listView;
	private List<CellDataItem> listCellData;
	private CustomCellAdapter _customAdapter;
	private final String TAG = "L3";
	
	private Handler _progressHandler;
	private AsyncFileLoader _fileLoader;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_download_manager); 
		
		btnBrowser = (Button)findViewById(R.id.btnBrowser);
		btnNew = (Button)findViewById(R.id.btnNew);
		btnPause = (Button) findViewById(R.id.btnPause);
		listView = (ListView) findViewById(R.id.listView);
		
		listCellData = new ArrayList<CellDataItem>();

		_customAdapter = new CustomCellAdapter(this,R.layout.listview_cell, listCellData);
		listView.setAdapter(_customAdapter);
		
		btnBrowser.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intentActivityBrowser = new Intent(DownloadManager.this,browserdownload.class);
				startActivityForResult(intentActivityBrowser, 1);
			}
		});
		
		btnNew.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intentNewDownload = new Intent(DownloadManager.this,newdownload.class);
				startActivityForResult(intentNewDownload, 2);
			}
		});
		
		btnPause.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				
			}
		});
		
		_progressHandler = new Handler(){
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				Log.d("L3","MSG "+msg);
			}
		};
		
		_progressHandler.sendEmptyMessage(0);	
	}
	

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		Log.d(TAG,"DownloadManager requestCode "+requestCode+" resultCode" +resultCode);
		
		// TODO Auto-generated method stub
		if(requestCode==1 || resultCode==1)
		{
			//back from browser
		}
		else if(requestCode==2 || resultCode==2)
		{
			//back from new download
			for(String url : data.getStringArrayExtra("url"))
			{
				Log.d(TAG,url);
				CellDataItem dataItem = new CellDataItem(listView);
				dataItem._parent = DownloadManager.this;
				try {
					dataItem.setURL(url);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					Log.d("L3","CellDataItem " + e.getMessage());
				}
				
				listCellData.add(dataItem);
			}
			
			_customAdapter = new CustomCellAdapter(this,R.layout.listview_cell, listCellData);
			listView.setAdapter(_customAdapter);

//			//begin sample download single file
//			initFileLoader(data.getStringExtra("url"));			
//			
//			_progressHandler = new Handler(){
//				public void handleMessage(Message msg) {
//					super.handleMessage(msg);
//					if (_fileLoader.isCancelled()) {
//						Log.d(TAG, "load cancelled");
//					}
//					else if (_fileLoader.getStatus() == AsyncTask.Status.FINISHED) {
//						Log.d(TAG, "load finished");
//					}
//					else {
////						_progressDialog.setProgress(_fileLoader.getLoadedBytePercent());
////						_progressDialog.setProgressNumberFormat(_fileLoader.getProgressDownload()); //get % download
////						Log.d(TAG, "progress download: " + _fileLoader.getLoadedBytePercent() + "/100");// get bytes download
//						Log.d(TAG, _fileLoader.getProgressDownload());
//						_progressHandler.sendEmptyMessageDelayed(0, 100);
//					}
//				}
//			};
//			
//			_progressHandler.sendEmptyMessage(0);
		}
		
		super.onActivityResult(requestCode, resultCode, data);
	}
//
//	@Override
//	protected void onPause() {
//		// TODO Auto-generated method stub
//		super.onPause();
//		cancelLoad();
//	}
//	
//	@Override
//	protected void onStop() {
//		// TODO Auto-generated method stub
//		super.onStop();
//		cancelLoad();
//	}
//	
//	private void cancelLoad() {
//		if (_fileLoader != null) {
//			_fileLoader.cancel(true);
//		}
//		
//	}
//	
	//Initial single download include:
	// - create path output
	// start file loader
	private void initFileLoader(String url) {
		// TODO Auto-generated method stub
		
		String filename = getFilenameURL(url);
		String subFolderName = checkDirectoryForFilename(filename);
		
		File sdcard = Environment.getExternalStorageDirectory();
		File directory = new File(sdcard.getAbsolutePath() + "/DownloadFolder/" + subFolderName);
		if (directory.exists() == false) {
			directory.mkdirs();
		}
		
		Log.d(TAG, "url download:" + url);
		File outputfile = new File(directory, filename);
		_fileLoader = new AsyncFileLoader(url, outputfile);
		_fileLoader.execute();
	}
	
	public String getFilenameURL(String url){
		// get last element of URL seperated by "/"
		String[] arrayComponents = url.split("/");
		String filename = arrayComponents[arrayComponents.length - 1];
		return filename;
	}
	
	public String getExtensionFile(String filename){
		String[] arrayComponents = filename.split("\\.");
		String extensionName = arrayComponents[arrayComponents.length - 1];
		return extensionName;
	}
	
	public String checkDirectoryForFilename(String filename){
		String folderName = "";
		String extensionName = getExtensionFile(filename);
		
		if (extensionName.equals("zip") || extensionName.equals("rar") || extensionName.equals("7z")) {//file
			//type compressed
			folderName = "Compressed";
		} 
		else if ( extensionName.equals("doc") || extensionName.equals("pdf") || extensionName.equals("ppt")
				|| extensionName.equals("xls")) { // file type documents
			folderName = "Document";
		}		
		else if ( extensionName.equals("mp3") || extensionName.equals("wav") || extensionName.equals("wma")
				|| extensionName.equals("aac") || extensionName.equals("aif") 
				|| extensionName.equals("m4a")){ // file type music
			folderName = "Music";
		}
		else if ( extensionName.equals("exe") || extensionName.equals("msi") || extensionName.equals("apk")
				){ // file type program
			folderName = "Program";
		}
		else if ( extensionName.equals("avi") || extensionName.equals("mpeg") || extensionName.equals("wmv")
				|| extensionName.equals("mp4") || extensionName.equals("m4v") || extensionName.equals("ogg"))
		{ // file type video
			folderName = "Video";
		}
		else if ( extensionName.equals("jpg") || extensionName.equals("jpeg") || extensionName.equals("png")
				){ // file type image
			folderName = "Picture";
		}
		else {// file type general
			folderName = "General";
		}
		
		return folderName;
	}
}
